<template>
  <div class="operation-log">
    <el-card class="main-card">
      <template #header>
        <div class="card-header">
          <span>操作日志</span>
          <div class="header-actions">
            <el-button
              type="danger"
              :disabled="selectedLogs.length === 0"
              @click="handleBatchDelete"
            >
              <el-icon><Delete /></el-icon>
              批量删除
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索条件 -->
      <el-form
        :model="searchForm"
        ref="searchFormRef"
        :inline="true"
        class="search-form"
        @submit.prevent="handleSearch"
      >
        <el-form-item label="用户名">
          <el-input
            v-model="searchForm.username"
            placeholder="请输入用户名"
            clearable
          />
        </el-form-item>
        <el-form-item label="操作类型">
          <el-select
            v-model="searchForm.action"
            placeholder="请选择操作类型"
            clearable
          >
            <el-option label="查看" value="VIEW" />
            <el-option label="创建" value="CREATE" />
            <el-option label="更新" value="UPDATE" />
            <el-option label="删除" value="DELETE" />
            <el-option label="登录" value="LOGIN" />
            <el-option label="登出" value="LOGOUT" />
            <el-option label="注册" value="REGISTER" />
          </el-select>
        </el-form-item>
        <el-form-item label="资源类型">
          <el-input
            v-model="searchForm.resource"
            placeholder="请输入资源类型"
            clearable
          />
        </el-form-item>
        <el-form-item label="IP地址">
          <el-input
            v-model="searchForm.ip"
            placeholder="请输入IP地址"
            clearable
          />
        </el-form-item>
        <el-form-item label="操作时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 操作日志列表 -->
      <el-table
        :data="logList"
        v-loading="loading"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="action" label="操作类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getActionTagType(row.action)">
              {{ getActionText(row.action) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="resource" label="资源类型" width="120" />
        <el-table-column prop="method" label="请求方法" width="100">
          <template #default="{ row }">
            <el-tag :type="getMethodTagType(row.method)">
              {{ row.method }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="path" label="请求路径" show-overflow-tooltip />
        <el-table-column prop="ip" label="IP地址" width="150" />
        <el-table-column prop="status" label="状态码" width="80">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="操作时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              @click="handleViewDetail(row)"
            >
              详情
            </el-button>
            <el-button
              type="danger"
              link
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 日志详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="操作日志详情"
      width="600px"
      @close="handleDetailDialogClose"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="ID">{{ currentLog.id }}</el-descriptions-item>
        <el-descriptions-item label="用户ID">{{ currentLog.userId }}</el-descriptions-item>
        <el-descriptions-item label="用户名">{{ currentLog.username }}</el-descriptions-item>
        <el-descriptions-item label="IP地址">{{ currentLog.ip }}</el-descriptions-item>
        <el-descriptions-item label="User-Agent">{{ currentLog.userAgent }}</el-descriptions-item>
        <el-descriptions-item label="请求方法">
          <el-tag :type="getMethodTagType(currentLog.method)">
            {{ currentLog.method }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="请求路径">{{ currentLog.path }}</el-descriptions-item>
        <el-descriptions-item label="操作类型">
          <el-tag :type="getActionTagType(currentLog.action)">
            {{ getActionText(currentLog.action) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="资源类型">{{ currentLog.resource }}</el-descriptions-item>
        <el-descriptions-item label="状态码">
          <el-tag :type="getStatusTagType(currentLog.status)">
            {{ currentLog.status }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="操作时间">{{ formatDate(currentLog.createdAt) }}</el-descriptions-item>
        <el-descriptions-item label="详情">{{ currentLog.details }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import { Delete, Search, Refresh } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'
import type { OperationLogListItem, OperationLogDetail } from '../../../types/api/operationLog'
import { operationLogApi } from '../../../api/modules/operationLog'
import { formatDate } from '../../../utils'

// 搜索表单
const searchForm = reactive({
  username: '',
  action: '',
  resource: '',
  ip: ''
})

// 日期范围
const dateRange = ref<[string, string]>(['', ''])

// 搜索表单引用
const searchFormRef = ref<FormInstance>()

// 加载状态
const loading = ref(false)

// 操作日志列表
const logList = ref<OperationLogListItem[]>([])

// 分页信息
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 选中的日志
const selectedLogs = ref<OperationLogListItem[]>([])

// 详情对话框可见性
const detailDialogVisible = ref(false)

// 当前查看的日志详情
const currentLog = ref<OperationLogDetail>({
  id: 0,
  userId: 0,
  username: '',
  ip: '',
  userAgent: '',
  method: '',
  path: '',
  action: '',
  resource: '',
  status: 0,
  details: '',
  createdAt: ''
})

// 获取操作日志列表
const getLogList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      pageSize: pagination.pageSize,
      username: searchForm.username,
      action: searchForm.action,
      resource: searchForm.resource,
      ip: searchForm.ip,
      startDate: dateRange.value[0],
      endDate: dateRange.value[1]
    }

    const response = await operationLogApi.getLogList(params)
    logList.value = response.data.data.list
    pagination.total = response.data.data.total
  } catch (error) {
    ElMessage.error('获取操作日志列表失败')
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  pagination.page = 1
  getLogList()
}

// 处理重置
const handleReset = () => {
  searchForm.username = ''
  searchForm.action = ''
  searchForm.resource = ''
  searchForm.ip = ''
  dateRange.value = ['', '']
  pagination.page = 1
  getLogList()
}

// 处理分页大小变化
const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  getLogList()
}

// 处理当前页变化
const handleCurrentChange = (val: number) => {
  pagination.page = val
  getLogList()
}

// 处理选择变化
const handleSelectionChange = (val: OperationLogListItem[]) => {
  selectedLogs.value = val
}

// 处理查看详情
const handleViewDetail = async (log: OperationLogListItem) => {
  try {
    const response = await operationLogApi.getLogDetail(log.id)
    currentLog.value = response.data.data
    detailDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取日志详情失败')
  }
}

// 处理关闭详情对话框
const handleDetailDialogClose = () => {
  currentLog.value = {
    id: 0,
    userId: 0,
    username: '',
    ip: '',
    userAgent: '',
    method: '',
    path: '',
    action: '',
    resource: '',
    status: 0,
    details: '',
    createdAt: ''
  }
}

// 处理删除
const handleDelete = (log: OperationLogListItem) => {
  ElMessageBox.confirm(
    `确定要删除操作日志 "${log.id}" 吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await operationLogApi.deleteLog(log.id)
      ElMessage.success('删除成功')
      await getLogList()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 处理批量删除
const handleBatchDelete = () => {
  if (selectedLogs.value.length === 0) {
    ElMessage.warning('请先选择要删除的日志')
    return
  }

  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedLogs.value.length} 条操作日志吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const ids = selectedLogs.value.map((log: OperationLogListItem) => log.id)
      await operationLogApi.batchDeleteLogs(ids)
      ElMessage.success('批量删除成功')
      await getLogList()
    } catch (error) {
      ElMessage.error('批量删除失败')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 获取操作类型标签类型
const getActionTagType = (action: string) => {
  switch (action) {
    case 'CREATE':
      return 'success'
    case 'UPDATE':
      return 'warning'
    case 'DELETE':
      return 'danger'
    case 'LOGIN':
      return 'primary'
    case 'LOGOUT':
      return 'info'
    case 'VIEW':
      return ''
    default:
      return 'info'
  }
}

// 获取操作类型文本
const getActionText = (action: string) => {
  switch (action) {
    case 'CREATE':
      return '创建'
    case 'UPDATE':
      return '更新'
    case 'DELETE':
      return '删除'
    case 'LOGIN':
      return '登录'
    case 'LOGOUT':
      return '登出'
    case 'REGISTER':
      return '注册'
    case 'VIEW':
      return '查看'
    default:
      return action
  }
}

// 获取请求方法标签类型
const getMethodTagType = (method: string) => {
  switch (method) {
    case 'GET':
      return ''
    case 'POST':
      return 'success'
    case 'PUT':
      return 'warning'
    case 'DELETE':
      return 'danger'
    default:
      return 'info'
  }
}

// 获取状态码标签类型
const getStatusTagType = (status: number) => {
  if (status >= 200 && status < 300) {
    return 'success'
  } else if (status >= 400 && status < 500) {
    return 'warning'
  } else if (status >= 500) {
    return 'danger'
  } else {
    return 'info'
  }
}

// 初始化
onMounted(() => {
  getLogList()
})
</script>

<style scoped lang="scss">
.operation-log {
  .main-card {
    margin-bottom: 20px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .search-form {
      margin-bottom: 20px;
      padding: 20px;
      background-color: #f5f7fa;
      border-radius: 4px;
    }
  }

  .pagination-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
  }
}
</style>
